package com.bjwl.web.contrlller;

import org.apache.commons.io.FilenameUtils;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @Author: dzx
 * @Date:Create：in 2020/4/12 15:54
 * @Description:
 * @Modified By：
 * @Version: 1.0
 */
@RestController
@RequestMapping("/image")
public class ImageController {

    /**
     * 上传图片返回url ,
     */
    @RequestMapping("/addImage")
    public String addImage(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request) throws IOException {
        //使用UUID给图片重命名，并去掉四个“-”
        String name = UUID.randomUUID().toString().replaceAll("-", "");
        //获取文件的扩展名
        String ext = FilenameUtils.getExtension(file.getOriginalFilename());
        //设置图片上传路径
        String url = request.getSession().getServletContext().getRealPath("/static/upload");
        System.out.println(url);
        //以绝对路径保存重名命后的图片
        file.transferTo(new File(url+"/"+name + "." + ext));

        //user.setImageURL("/static/upload/"+name + "." + ext);
        String path = "/static/upload/"+name+"."+ext;
        return path;
    }
}
